<?php
require_once "Zend/Db/Table.php";
class Resume extends Zend_Db_Table {

    protected $_name = 'resume';
    const UPLOADED_FILES_PATH = '/public/pictures/resume/';

    
    /**
     * Retrieve datas of  a specific resume from database
     *
     * @param Zend_Controller_Action $action
     * @return Zend_Db_Table_Row_Abstract $resume
     * @throws Exception_Controller_No_Param, Exception_Db_No_Row
     */
    public function fetchResume(Zend_Controller_Action $action){

        $id = $this->getResumeId($action);
        if(!is_int($id) || $id <= 0){
            require_once('exceptions/Exception_Controller_No_Param.php');
            throw new Exception_Controller_No_Param('Missing requested paramemters or invalid parameters provided via GET or POST. ');
        }
        if(!$resume = $this->fetchRow('id = '.$id)){
            require_once('exceptions/Exception_Db_No_Row.php');
            throw new Exception_Db_No_Row('No row fetched from database.');

        }

        $content = unserialize($resume->content);
        foreach($content as $key => $value){

            $content[$key] = nl2br($value);
        }
        $resume->content = $content;

        return $resume;
    }

    public function isResumeOwner(Zend_Controller_Action  $action){

        $auth = Zend_Auth::getInstance();
        
        $row = $this->fetchRow('id = '.$this->getResumeId($action));
        if($row->user_id != $auth->getIdentity()->id)
        return false;
        else
        return true;
    }
    
    public function getResumeId(Zend_Controller_Action  $action){
        
        if($action->getRequest()->isPost()) 
        $id = (int)$action->getRequest()->getPost('id');
        else
        $id = (int)$action->getRequest()->getParam('id');
        return $id;
    }
    
    

    public function createResume(){

         
        Zend_Loader::loadClass('PostFilter');
        PostFilter::filter();
         
        $user = Zend_Auth::getInstance()->getIdentity();

        $data = array(
                'user_id' => $user->id,
                'title' => $_POST['title'],
                'content' => serialize(array_splice($_POST, -1, 4)),
                'created' => time(),
                'edited'  => time(), 
        );
        $this->insert($data);


    }

    /**
     * Retrieve datas of a resume, preparing for the 'view' action
     *
     * @param Zend_Controller_Action $action
     * @return array $content
     */
    public function viewResume(Zend_Controller_Action $action){

        $resume = $this->fetchResume($action);
        $content = $resume->content;

        return $content;
    }

    public function updateResume($id){

        if($id > 0){

            $data = array(
                    'title' => $_POST['title'],
                    'content' => serialize($_POST),
                    'edited' => time(), 
            );
            $this->update($data,'id = '.$id);
        }
    }

    /**
     * Send resume by email
     *
     * @param int $id
     */
    public function sendResume(Zend_Controller_Action $action){


        $resume = $this->fetchResume($action);
        $content = $resume->content;

        Zend_Loader::loadClass('Zend_Mail');
        $mail = new Zend_Mail('UTF-8');
        $mail->setType('text/html')
        ->setFrom('mail@rs.zidon.net', 'rs.zidon.net(Online Resume Maker)')
        ->addTo($addrs)
        ->setSubject($_POST['subject'])
        ->setBodyHtml($action->view->render('/resume/_resume.phtml'))
        ->send();
    }

    /**
     * Output the resume as a PDF file
     *
     * @param Zend_Controller_Action $action
     *
     */
    public function outputResumePdf(Zend_Controller_Action $action){

        Zend_Loader::loadClass('Zend_Pdf');
        $pdf = new Zend_Pdf();
        $pdf->pages = array_reverse($pdf->pages);
        $page = Zend_Pdf::newPage(zend_pdf_Page::SIZE_A4);
        $pdf->pages[] = $page;

        $resume = $this->fetchResume($action);
        $content = $resume->content;
        $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_BOLD),18);

        $pos_x = 50;
        $pos_y = (842 - 50);

        /**
         * Move the pointer of the PDF Writer to the next line
         *
         * @param float height of the line
         * @param float current position of y
         *
         */
        function nextLine($lineHeight, &$pos_y){

            $pos_y -= $lineHeight;

        }

        $page->drawText($content['first_name'].' '.$content['surname'], $pos_x ,$pos_y ,'UTF-8');
        $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_ITALIC),12);

        //Draw Contact Information
        nextLine(18,$pos_y);
        $page->drawText($content['street_address'].', '.$content['city'].', '.$content['state'].' '.$content['postcode'],$pos_x,$pos_y,'UTF-8');
        nextLine(15,$pos_y);
        $page->drawText('Phone: '.$content['phone'], $pos_x, $pos_y, 'UTF-8');
        nextLine(15,$pos_y);
        $page->drawText('Mobile: '.$content['mobile'], $pos_x, $pos_y, 'UTF-8');
        nextLine(15,$pos_y);
        $page->drawText('Email: '.$content['email'], $pos_x, $pos_y, 'UTF-8');

        //Draw Parts of Objective, Qualifications, Education, Experience, Skills
        nextLine(30,$pos_y);


        $parts = array(
        'objective' => $content['objective'], 
        'qualifications' => $content['qualifications'], 
        'education' => $content['education'], 
        'experience' => $content['experience'], 
        'skills' => $content['skills'],

        );

        foreach($parts as $key => $value){

            $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_BOLD),14);



            $page->drawText(ucfirst($key).':',$pos_x,$pos_y,'UTF-8');
            nextLine(5,$pos_y);
            $page->setLineWidth(2);
            $page->drawLine($pos_x,$pos_y,595-$pos_x,$pos_y);

            nextLine(15,$pos_y);
            $page->setFillColor(new Zend_Pdf_Color_Rgb(0,0,0));
            $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER),10);
            $objLines = explode("\n",$value);


            foreach($objLines as $objLine){


                $page->drawText($objLine,$pos_x,$pos_y,'UTF-8');
                nextLine(12,$pos_y);
            }
            nextLine(15,$pos_y);
        }
        //References as required

        $page->setFont(Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER_ITALIC),12);
        $page->drawText('*References As Required*',$pos_x,60,'UTF-8');

        //Set properties of PDF document
        $pdf->properties = array(
                          'Creator' => 'http://rs.zidon.net (Online Resume Maker)',
                          'Title'   => $content['title'],
                          'Author'  => $content['first_name'].' '.$content['surname'],
        );
        //Output PDF file for downloading
        $pdfData = $pdf->render();

        header("Content-Disposition: attachment;filename=".$content['title'].".pdf");
        header("Content-type: application/x-pdf");
        echo $pdfData;
        exit();

    }

}
